package mongo
import (
	"context"
	"errors"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"time"
)
type Database  = *mongo.Database
type Collection = *mongo.Collection
var collection Database
var err error

//ConnectToDB
func connectToDB(url ,name string,timeout time.Duration,num uint64)(Database,error)  {
	ctx,cancel := context.WithTimeout(context.Background(),timeout)
	defer cancel()
	o := options.Client().ApplyURI(url)
	o.SetMaxPoolSize(num)
	client, err := mongo.Connect(ctx,o)
	if err != nil{
		return nil,err
	}
	return client.Database(name),nil
}
func init()  {
	collection, err = connectToDB("mongodb://localhost:27017","sinima",5*time.Second,5000)
	if err != nil{
		return
	}
}
//Get collection
func Get()(Database,error)  {
	if collection != nil{
		return  collection,nil
	}
	return nil,errors.New("数据库连接错误")
}